package com.atguigu.gmall.order.biz.impl;/*
 * @author: XueYouPeng
 * @time: 23.7.28 下午 4:17
 */
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.atguigu.gmall.cart.entity.CartItem;
import com.atguigu.gmall.common.constant.GmallConstant;
import com.atguigu.gmall.common.feign.cart.CartFeignClient;
import com.atguigu.gmall.common.feign.user.UserFeignClient;
import com.atguigu.gmall.common.feign.util.AuthUserInfoUtils;
import com.atguigu.gmall.common.feign.ware.WareFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.order.entity.OrderDetail;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import com.atguigu.gmall.order.service.OrderDetailService;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.order.vo.DetailVo;
import com.atguigu.gmall.user.entity.UserAddress;


import com.atguigu.gmall.order.biz.OrderBizService;
import com.atguigu.gmall.order.vo.OrderConfirmVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderBizServiceImpl implements OrderBizService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient ;

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Autowired
    private WareFeignClient wareFeignClient ;

    @Autowired
    private OrderInfoMapper orderInfoMapper ;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public OrderConfirmVo submitOrder() {

        log.info("OrderBizServiceImpl...submitOrder方法执行了");

        //   远程调用service-user微服务的接口查询当前登录用户的收货人地址信息
        Result<List<UserAddress>> listResult = userFeignClient.findUserAddressByUserId();
        List<UserAddress> userAddressList = listResult.getData();

        //  远程调用service-cart微服务的接口查询当前登录用户的购物车数据
        Result<List<CartItem>> selectedCartItem = cartFeignClient.findAllSelectedCartItem();
        List<CartItem> cartItemList = selectedCartItem.getData();
        List<DetailVo> detailVoList = cartItemList.stream().map(cartItem -> {
            DetailVo detailVo = new DetailVo();
            detailVo.setImgUrl(cartItem.getImgUrl());
            detailVo.setSkuName(cartItem.getSkuName());
            detailVo.setOrderPrice(cartItem.getCartPrice());
            detailVo.setSkuNum(cartItem.getSkuNum());
            detailVo.setSkuId(cartItem.getSkuId());

            // 远程调用ware-manage库存微服务的接口获取当前商品是否存在库存的状态数据
            String hasStock = wareFeignClient.hasStock(cartItem.getSkuId(), cartItem.getSkuNum());
            detailVo.setHasStock(hasStock);
            return detailVo;
        }).collect(Collectors.toList());

        // 记录商品总数量
        Integer totalNum = detailVoList.stream().map(detailVo -> detailVo.getSkuNum()).reduce((o1, o2) -> o1 + o2).get();

        //商品总金额 需要计算
        BigDecimal totalAmount = detailVoList.stream().map(detailVo -> detailVo.getOrderPrice().multiply(new BigDecimal(detailVo.getSkuNum())))
                .reduce((o1, o2) -> o1.add(o2)).get();

        //创建一个外部交易号
        String tradeNo = UUID.randomUUID().toString().replace("-", "");

        //构建响应结果
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        orderConfirmVo.setDetailArrayList(detailVoList);
        orderConfirmVo.setTotalNum(totalNum);
        orderConfirmVo.setTotalAmount(totalAmount);
        orderConfirmVo.setUserAddressList(userAddressList);
        orderConfirmVo.setTradeNo(tradeNo);

        //把外部交易号保存到Redis中
        redisTemplate.opsForValue().set(GmallConstant.REDIS_ORDER_CONFIRM + tradeNo , "1" , 30 , TimeUnit.MINUTES);


        return orderConfirmVo;
    }

    @Override
    public OrderInfo findOrderInfo(Long orderId) {

        //根据订单的id以及用户id 查询数据
        String userId = AuthUserInfoUtils.getAuthUserInfo().getUserId();
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getId , orderId) ;
        lambdaQueryWrapper.eq(OrderInfo::getUserId , Long.parseLong(userId)) ;
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);

        return orderInfo;
    }

    @Override
    public String saveOrderInfo(OrderInfo orderInfo) {

        // 保存订单数据
        orderInfoMapper.insert(orderInfo);

        // 保存明细数据
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        orderDetailList = orderDetailList.stream().map(orderDetail -> {
            orderDetail.setOrderId(orderInfo.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetailList);

        //返回的是orderId
        Long orderInfoId = orderInfo.getId();
        String orderInfoIdStr = String.valueOf(orderInfoId);
        return orderInfoIdStr;
    }
}

















